package com.melon.modules.test.web;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@Controller
@RequestMapping("/test/media")
public class FileUploadController {

    @RequestMapping(value = {"/upload/form"}, method = RequestMethod.GET)
    public String handleForm() throws IOException {
        return "uploadFailure";
    }


    @ResponseBody
    @RequestMapping(value = {"/upload/form"}, method = RequestMethod.POST)
    public Object handleFormUpload(
            @RequestParam(value = "name") String name,
            @RequestParam(value = "file") MultipartFile file) throws IOException {

        if (file != null && !file.isEmpty()) {
            byte[] bytes = file.getBytes();
            // store the bytes somewhere
            System.out.println(file.getName());
            return "redirect:uploadSuccess";
        }

        return "redirect:uploadFailure";
    }

}
